package com.virtual.api.zb.service;

import com.alibaba.fastjson.JSONObject;
import com.virtual.api.zb.kits.EncryDigestUtil;
import com.virtual.api.zb.kits.HttpUtilManager;
import com.virtual.api.zb.kits.MapSort;
import com.virtual.api.zb.pojo.VirtualCurrencyMarketDTO;
import org.apache.http.HttpException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class RequestApiService {
    private static final String  ACCESS_KEY = "ee500a5f-c45f-4880-bbb9-b172603e2fb1";
    private static final String SECRET_KEY = "21e12798-e633-4c80-8df8-b4cd8e5752f5";
    private static final String URL_PREFIX = "https://trade.zb.com/api/";
    private static final String API_DOMAIN = "http://api.bitkk.com";
    private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
    private static final String UTF8 = "utf-8";

    private static final Logger LOGGER = LoggerFactory.getLogger(RequestApiService.class);

    /**'
     * 通过币种请求对应行情信息
     * @param currency 币种
     * @return 币种行情信息
     */
    public VirtualCurrencyMarketDTO getMarket(String currency) {
        // 请求地址
        String url = API_DOMAIN + "/data/v1/ticker?market=" + currency;
        String response = get(url, UTF8);
        return response != null ? JSONObject.parseObject(response, VirtualCurrencyMarketDTO.class) : null;
    }

    /**
     * 委托下单
     * @param price 单价
     * @param amount 数量
     * @param tradeType 交易类型（1/0[buy/sell])
     * @param acctType 杠杠 1/0[杠杠/现货](可选参数,默认为: 0 现货)
     * @param currency 币种
     * @return 请求响应结果
     */
    public String order(String price, String amount, String tradeType, String acctType, String currency) {
        Map<String, String> params = new HashMap<>();
        params.put("method", "order");
        params.put("price", price);
        params.put("amount", amount);
        params.put("tradeType", tradeType);
        params.put("acctType", acctType);
        params.put("currency", currency);
        return getJsonPost(params);
    }

    /**
     * 获取委托买单或卖单
     * @param orderId 委托单号
     * @return 请求响应结果
     */
    public String getOrder(String orderId) {
        Map<String, String> params = new HashMap<>();
        params.put("method", "getOrder");
        params.put("id", orderId);
        return getJsonPost(params);
    }

    /**
     * 取消委托
     * @param currency 币种
     * @param orderId 订单号
     * @return 请求响应结果
     */
    public String cancelOrder(String currency, String orderId) {
        Map<String, String> params = new HashMap<>();
        params.put("method", "cancelOrder");
        params.put("id", orderId);
        params.put("currency", currency);

        return getJsonPost(params);
    }

    /**
     * 获取json内容(统一加密)
     *
     * @param params 请求参数
     * @return 请求结果
     */
    public static String getJsonPost(Map<String, String> params) {
        params.put("accesskey", ACCESS_KEY); // 这个需要加入签名,放前面
        String digest = EncryDigestUtil.digest(SECRET_KEY);

        String sign = EncryDigestUtil.hmacSign(MapSort.toStringMap(params), digest); // 参数执行加密
        String method = params.get("method");

        // 加入验证
        params.put("sign", sign);
        params.put("reqTime", System.currentTimeMillis() + "");
        String url = "请求地址:" + URL_PREFIX + method + " 参数:" + params;
        LOGGER.info(url);
        String json = "";
        try {
            json = HttpUtilManager.getInstance().requestHttpPost(URL_PREFIX, method, params);
        } catch (HttpException | IOException e) {
            LOGGER.error("获取交易json异常：", e.getMessage());
        }
        return json;
    }

    /**
     * 请求get方式接口
     * @param urlAll 请求接口地址
     * @param charset 编码
     * @return 请求响应结果
     */
    public static String get(String urlAll, String charset) {
        BufferedReader reader = null;
        String result = null;
        StringBuilder builder = new StringBuilder();
        try {
            URL url = new URL(urlAll);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setReadTimeout(30000);
            connection.setConnectTimeout(30000);
            connection.setRequestProperty("User-agent", USER_AGENT);
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, charset));
            String strRead;
            while ((strRead = reader.readLine()) != null) {
                builder.append(strRead);
                builder.append("\r\n");
            }

            result = builder.toString();
        } catch (Exception e) {
            LOGGER.error("请求接口[{}],发生异常：{}", urlAll, e.getMessage());
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                LOGGER.error("释放资源发生异常：{}", e.getMessage());
            }
        }
        return result;
    }
}
